#!/bin/bash
# ===== Log =====
# log.info xxx
# log.warn xxx
# log.info xxx
# log.debug xxx
# 带颜色的echo
log.warn() { echo -e "[\e[33mWARN\e[0m]:  \e[1m$*\e[0m"; }
log.error()  { echo -e "[\e[31mERROR\e[0m]: \e[1m$*\e[0m"; }
log.info() { echo -e "[\e[96mINFO\e[0m]:  \e[1m$*\e[0m"; }
log.debug()  { echo -e "[\e[32mDEBUG\e[0m]: \e[1m$*\e[0m"; }


# echo -e "\e[30m 黑色 \e[0m"
# echo -e "\e[31m 红色 \e[0m"
# echo -e "\e[32m 绿色 \e[0m"
# echo -e "\e[33m 黄色 \e[0m"
# echo -e "\e[34m 蓝色 \e[0m"
# echo -e "\e[35m 紫色 \e[0m"
# echo -e "\e[36m 青色 \e[0m"
# echo -e "\e[37m 白色 \e[0m"


############################################################################开始
if [ "$UID" != "0" ];then
log.error "Need to be run as root."
exit 1
fi
# 检查参数个数
if [ "$#" -ne 2 ]; then
    log.info "Usage: $0 desktop-file/package-name <desktop-file>/<packagename>"
    exit 1
fi

####################################变量配置（用于后续支持多个包管理系统）
# 清除先前的变量值
unset ABSOLUTE_PATH PKGNAME_GUESS DPKG_LIST_FILE ACE_ENV_PATH

if [[ "$1" = "package-name" ]];then
            apt purge $2 -y
		ret=$?
		if [ "$ret" = "0" ];then
			log.info "Operation succeeded."
			exit 0
		else
			log.error "Operation failed."
			exit $ret
		fi
elif [[ "$1" = "desktop-file" ]];then
####################################验证输入有效性
# 保存并验证绝对路径
ABSOLUTE_PATH=$(realpath $2)
ABSOLUTE_PATH_NO_REALPATH=$2

log.debug "ABSOLUTE_PATH=$(realpath $2)"
log.debug "ABSOLUTE_PATH_NO_REALPATH=$2"
# 验证是否为desktop文件
	if [ ! -e $ABSOLUTE_PATH ];then
         log.error "$ABSOLUTE_PATH does not exist. May have already been uninstalled"
		exit 1
    fi
    if [[ ! $ABSOLUTE_PATH == *.desktop ]]; then
    		log.error "The file is not a desktop file."
    		exit 1
	fi


#############################################转发请求去ACE不同的卸载器

### 这里面全是屎
# ACE 卸载器需要一个/usr/share的地址，但是暴露给主机的是一个data-dir
# 后续可能需要改一下策略，这个东西是为了避免主机被ACE的环境影响做的
# 也可能一直这样屎下去，反正用户无感
# 1. 检查已有的环境
# 查找/opt/apps/目录下以amber-ce-开头的目录
ACE_ENV_PATHS=$(find "/opt/apps" -maxdepth 1 -name "amber-ce-*")
log.info $ACE_ENV_PATHS
# 2. 合成路径并进行匹配
for ACE_ENV_PATH in $ACE_ENV_PATHS; do
    # 提取关键词（amber-ce-后面的部分）
    KEYWORD=$(basename "$ACE_ENV_PATH" | sed 's/^amber-ce-//')
    # 合成路径
    COMBINED_PATH="/opt/apps/amber-ce-$KEYWORD/files/ace-env"
    MODIFIED_PATH="${ABSOLUTE_PATH_NO_REALPATH//\/flamescion-container-tools\/data-dir\//\/usr\/share\/}"
    # 这里如果不考虑cn.flamescion.... 的话是直接用realpath的，不需要手动替换，直接ABSOLUTE_PATH了
    log.info ${MODIFIED_PATH}
    # 3. 逐条验证$ABSOLUTE_PATH_NO_REALPATH变量是否以合成路径开头
    if [[ "$ABSOLUTE_PATH_NO_REALPATH" == "$COMBINED_PATH"* ]]; then
        # 如果匹配，执行uninstall-helper命令
        ace-"$KEYWORD"-uninstall-helper "${MODIFIED_PATH}"
        exit $?
    fi
done


################################## Deb卸载
# 检查dpkg列表文件
DPKG_INFO_PATH="/var/lib/dpkg/info"
if [ -f "$DPKG_INFO_PATH/$PKGNAME_GUESS.list" ]; then
    DPKG_LIST_FILE="$DPKG_INFO_PATH/$PKGNAME_GUESS.list"
elif ls "$DPKG_INFO_PATH/${PKGNAME_GUESS}:*.list" 1> /dev/null 2>&1; then
    DPKG_LIST_FILE=$(ls "$DPKG_INFO_PATH/${PKGNAME_GUESS}:*.list" | head -n 1)
else
     log.warn "No dpkg list file found for $PKGNAME_GUESS.desktop,try to scan to search for the package"
fi

# 验证文件并执行操作
if [ -f "$DPKG_LIST_FILE" ]; then

    if grep -q "$ABSOLUTE_PATH" "$DPKG_LIST_FILE" ; then
        apt purge $PKGNAME_GUESS -y
		ret=$?
		if [ "$ret" = "0" ];then
			log.info "Operation succeeded."
			exit 
		else
			log.error "Operation failed."
			exit $ret
		fi
			
    else
        log.error "Path not found in the dpkg list file,try to scan to search for the package"
    fi
fi
    # 遍历所有list文件 As fallback
    for file in "$DPKG_INFO_PATH"/*.list; do
        if grep -q "$ABSOLUTE_PATH" "$file"; then
            PKGNAME_GUESS=$(basename "$file" .list | cut -d':' -f1)
            log.info "Get pkgname $PKGNAME_GUESS, uninstalling..."
            apt purge $PKGNAME_GUESS -y
		ret=$?
		if [ "$ret" = "0" ];then
			log.info "Operation succeeded."
			exit 0
		else
			log.error "Operation failed."
			exit $ret
		fi
            
        fi
    done

#############################################最后是pkcon卸载
log.info"It  seems like a 3-rd party package manager app. Try pkcon uninstall..."
# 截取并保存包名
PKGNAME_GUESS=$(basename "$ABSOLUTE_PATH" .desktop)
        pkcon remove $PKGNAME_GUESS -y
		ret=$?
		if [ "$ret" = "0" ];then
			log.info "Operation succeeded."
			exit 
		else
			log.error "Operation failed"
            exit $ret
		fi


########如果所有的卸载都没有匹配，则报错退出

    log.error "Error: No matching package found."
    exit 1

else
log.error "Error: unknown option."
exit 1
fi
